<template>
  <el-dialog :title="isEdit ? '修改功能': '新增功能'" :visible.sync="visible" :close-on-click-modal="closeOnClickModal" @open="_handleDialogOpen" @close="_cancel">
    <el-form ref="dataForm" :model="form" :status-icon="true" :rules="formRules" label-width="100px">
      <el-form-item v-show="!!parentData" label="上级功能">
        <span>{{ parentData ? parentData.sysName : '' }}</span>
      </el-form-item>
      <el-form-item label="功能名称" prop="sysName">
        <el-input v-model="form.sysName" placeholder="请输入功能名称"/>
      </el-form-item>
      <el-form-item label="功能类型" prop="type">
        <el-radio-group v-model="form.type" @change="_handleTypeChange">
          <el-radio label="1">模块</el-radio>
          <el-radio label="2">功能</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否显示" prop="isMenu">
        <el-radio-group v-model="form.isMenu">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-show="form.type === '2'" label="打开方式" prop="openType">
        <el-radio-group v-model="form.openType">
          <el-radio label="1">弹框</el-radio>
          <el-radio label="2">页面</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item v-show="form.type === '1'" label="图标样式" prop="icon">
        <el-input v-model="form.icon" placeholder="请输入图标样式"/>
      </el-form-item> -->
      <el-form-item v-show="form.type === '1'" label="图标样式" prop="icon">
        <el-select v-model="form.icon" placeholder="请选择图标样式">
          <el-option
            v-for="(item, index) in iconList"
            :key="index"
            :label="item"
            :value="item">
            <span style="float: left"><svg-icon :icon-class="item" class="icon-demo"/></span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item }}</span>
          </el-option>
        </el-select>
        <svg-icon :icon-class="form.icon" class="icon-sel"/>
      </el-form-item>
      <el-form-item v-show="form.openType == '2'" label="URL" prop="path">
        <el-input v-model="form.path" placeholder="请输入URL"/>
      </el-form-item>
      <el-form-item v-show="form.openType == '2'" label="路由名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入路由名称（英文）"/>
      </el-form-item>
      <el-form-item v-show="form.openType == '2'" label="页面路径" prop="component">
        <el-input v-model="form.component" placeholder="请输入页面路径"/>
      </el-form-item>
      <el-form-item label="权限代码" prop="permissionCode">
        <el-input v-model="form.permissionCode" placeholder="请输入权限代码"/>
      </el-form-item>
      <el-form-item label="权限模式" prop="url">
        <el-input v-model="form.url" placeholder="请输入权限模式（ant path）"/>
      </el-form-item>
      <!-- <el-form-item label="可否分配" prop="isAssignable">
        <el-radio-group v-model="form.isAssignable">
          <el-radio label="0">不可分配</el-radio>
          <el-radio label="1">可以分配</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item label="排序号" prop="sortNo">
        <el-input-number v-model="form.sortNo" placeholder="请输入排序号"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="_cancel">取 消</el-button>
      <el-button :loading="_loading" size="small" type="primary" @click="_ok">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>

import { getFunctionById } from '@/api/systemManage/function'

export default {

  props: {
    closeOnClickModal: {
      type: Boolean,
      default: false
    },

    loading: {
      type: Boolean,
      default: false
    }
  },

  data() {
    return {
      iconList: [],
      parentData: null,
      isEdit: false,
      visible: false,
      form: {},
      formRules: {
        sysName: [{
          required: true,
          message: '请输入名称'
        }],
        path: [{
          validator: (rule, value, callback) => {
            if (value && !/^[-_0-9a-zA-Z\/]+/.test(value)) {
              callback(new Error('格式不正确，只能包含数字、字母、-、/和_'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        component: [{
          validator: (rule, value, callback) => {
            if (value && !/^[-_0-9a-zA-Z\/]+/.test(value)) {
              callback(new Error('格式不正确，只能包含数字、字母、-、/和_'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        permissionCode: [{
          validator: (rule, value, callback) => {
            if (value && !/[-_0-9a-zA-Z\/]+/.test(value)) {
              callback(new Error('格式不正确，只能包含数字、字母、-和_'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    '_loading': {
      get() {
        return this.loading
      },

      set(value) {
        this.$emit('update:loading', value)
      }
    }
  },
  created() {
    const req = require.context('@/icons/svg', false, /\.svg$/)
    req.keys().forEach(element => {
      if (/\.svg$/.test(element)) {
        this.iconList.push(element.replace(/.+\//, '').replace(/\.svg$/, ''))
      }
    })
  },
  methods: {
    _formReset() {
      this.form = {
        name: '',
        sysName: '',
        permissionCode: '',
        icon: '',
        path: '',
        hidden: false,
        alwaysShow: 1,
        component: '',
        noCache: false,
        url: '',
        type: '2',
        isMenu: '0',
        openType: '1',
        status: 1,
        level: 1,
        sortNo: 1
      }
      this.$nextTick(() => {
        this.$refs.dataForm.resetFields()
      })
    },

    _handleDialogOpen() {
      this._formReset()
      this.$emit('open')
    },

    _cancel() {
      this._formReset()
      this.visible = false
      this.isLoading = false
      this.$emit('cancel')
    },

    _ok() {
      const form = this.$refs['dataForm']
      form.validate(valid => {
        if (valid) {
          const formData = JSON.parse(JSON.stringify(this.form))
          // if (this.parentData) {
          //   formData.level = (this.parentData.level || 1) + 1
          //   formData.component = (formData.component || '').replace(/^\//, '')
          //   formData.path = (formData.path || '').replace(this.parentData.path, '').replace(/^\//, '')
          // } else {
          //   if (formData.path) {
          //     formData.path = ('/' + formData.path).replace('//', '/')
          //   }
          //   formData.level = 1
          // }

          this.$emit('ok', formData, this.isEdit)
        }
      })
    },

    _handleTypeChange(val) {
      if (val === '1') {
        this.form.isMenu = '1'
        this.form.openType = '2'
      } else {
        this.form.isMenu = '0'
        this.form.openType = '1'
      }
    },

    show(params, parent) {
      this.visible = true
      this.parentData = parent
      if (params) {
        this.isEdit = true
        getFunctionById({
          id: params.id
        }).then(resp => {
          this.form = resp.data
        }).catch(resp => {
          this.$message.error(resp.message)
        })
      } else {
        // pass
        this.isEdit = false
        // this._clear()
      }
    },

    close() {
      this._cancel()
    }
  }
}
</script>
<style lang="css" scoped>
  .icon-sel {
    width: 2.2em;
    height: 2.2em;
    margin-left: 10px;
  }
</style>
